package com.jh.paymentchannel.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.ump.exception.VerifyException;
import com.jh.paymentchannel.util.ump.paygate.v40.Mer2Plat_v40;
import com.jh.paymentchannel.util.ump.paygate.v40.Plat2Mer_v40;
import com.jnewsdk.util.SignUtil;

import net.sf.json.JSONObject;


@Controller
@EnableAutoConfiguration
public class SFCallBackService {

	private static final Logger log = LoggerFactory.getLogger(SFCallBackService.class);
	
	@Autowired
	Util util;
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/topup/sf/notify_call")
	public @ResponseBody void notifycall(HttpServletRequest request, HttpServletResponse response) throws IOException{
		log.info("into SFCallBackService  ================ "+request);
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
		Map<String, String> paramMap = SignUtil.parseParam(request);
		log.info("paramMap=============" + paramMap);
			JSONObject jsonInfo = JSONObject.fromObject(paramMap);
			log.info("jsonInfo=============" + jsonInfo.toString());
	       String resString = "fail" ;
	       if(jsonInfo.containsKey("trade_state")&&"SUCCESS".equalsIgnoreCase(jsonInfo.getString("trade_state"))){
	    	   String trade_no = jsonInfo.getString("trade_no");
	    	   String ordercode = jsonInfo.getString("out_trade_no");
	    	 //商户可加入自己的处理逻辑
               /**更新订单状态*/
				/**调用下单，需要得到用户的订单信息*/
				RestTemplate restTemplate=new RestTemplate();
				
				URI uri = util.getServiceUrl("transactionclear", "error url request!");
				String url = uri.toString() + "/v1.0/transactionclear/payment/update";
				
				/**根据的用户手机号码查询用户的基本信息*/
				MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("status", "1");
				requestEntity.add("third_code",   trade_no);
				requestEntity.add("order_code",   ordercode);
				String result = restTemplate.postForObject(url, requestEntity, String.class);
				
				/**判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
				uri = util.getServiceUrl("transactionclear", "error url request!");
				url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
				
				
				requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("order_code",   ordercode);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				
				JSONObject jsonObject =  JSONObject.fromObject(result);
				JSONObject resultObj  =  jsonObject.getJSONObject("result");
				String outMerOrdercode  =  resultObj.getString("outMerOrdercode");
				String orderdesc        =  resultObj.getString("desc");
				String phone            =  resultObj.getString("phone");
				String  tranamount      =  resultObj.getString("amount");
				String channelTag       =  resultObj.getString("channelTag");
				String notifyURL        =  resultObj.getString("outNotifyUrl");
				if(outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")){
					uri = util.getServiceUrl("channel", "error url request!");
					url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
					requestEntity  = new LinkedMultiValueMap<String, String>();
					requestEntity.add("merchant_no",  phone);
					requestEntity.add("amount",  tranamount);
					requestEntity.add("channel_tag",  channelTag);
					requestEntity.add("order_desc",  URLEncoder.encode(orderdesc, "UTF-8"));
					requestEntity.add("order_code",  outMerOrdercode);
					requestEntity.add("sys_order",   ordercode);
					requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
					result = restTemplate.postForObject(url, requestEntity, String.class);
				}
				resString = "SUCCESS" ;
	       }else if(jsonInfo.containsKey("status")&&"0".equals(jsonInfo.getString("status"))){
	    	   String ordercode = jsonInfo.getString("transactionId");
	    	   RestTemplate restTemplate=new RestTemplate();
				
				URI uri = util.getServiceUrl("transactionclear", "error url request!");
				String url = uri.toString() + "/v1.0/transactionclear/payment/update";
				
				/**根据的用户手机号码查询用户的基本信息*/
				MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("status", "1");
				requestEntity.add("third_code",   "");
				requestEntity.add("order_code",   ordercode);
				String result = restTemplate.postForObject(url, requestEntity, String.class);
				
				/**判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
				uri = util.getServiceUrl("transactionclear", "error url request!");
				url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
				
				
				requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("order_code",   ordercode);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				
				JSONObject jsonObject =  JSONObject.fromObject(result);
				JSONObject resultObj  =  jsonObject.getJSONObject("result");
				String outMerOrdercode  =  resultObj.getString("outMerOrdercode");
				String orderdesc        =  resultObj.getString("desc");
				String phone            =  resultObj.getString("phone");
				String  tranamount      =  resultObj.getString("amount");
				String channelTag       =  resultObj.getString("channelTag");
				String notifyURL        =  resultObj.getString("outNotifyUrl");
				if(outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")){
					uri = util.getServiceUrl("channel", "error url request!");
					url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
					requestEntity  = new LinkedMultiValueMap<String, String>();
					requestEntity.add("merchant_no",  phone);
					requestEntity.add("amount",  tranamount);
					requestEntity.add("channel_tag",  channelTag);
					requestEntity.add("order_desc",  URLEncoder.encode(orderdesc, "UTF-8"));
					requestEntity.add("order_code",  outMerOrdercode);
					requestEntity.add("sys_order",   ordercode);
					requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
					result = restTemplate.postForObject(url, requestEntity, String.class);
				}
				resString = "SUCCESS" ;
	       }else {
	    	   if(jsonInfo.containsKey("errMsg"))
	    		   log.info("交易失败："+jsonInfo.getString("errMsg"));
	    	   if(jsonInfo.containsKey("trade_state"))
	    		   log.info("交易失败："+jsonInfo.getString("trade_state"));
	        	resString = "fail";
	        }
	       PrintWriter write = response.getWriter();
	       write.print(resString);
	       write.flush();
	       
	}
		
	
}
